package week_four;

import java.util.*;

public class Twitter {
    private static int timestamp = 0;
    private Map<Integer, TweetNode> tweets;
    private Map<Integer, Set<Integer>> followings;
    private PriorityQueue<TweetNode> pq;

    private class TweetNode {
        TweetNode next;
        int ts;
        int tweetId;

        //        int userId;
        public TweetNode(int tweetId, int timestamp) {
            this.ts = timestamp;
            this.tweetId = tweetId;
        }
    }

    /**
     * Initialize your data structure here.
     */
    public Twitter() {
        tweets = new HashMap<>();
        followings = new HashMap<>();
        pq = new PriorityQueue<>(((o1, o2) -> o2.ts - o1.ts));
    }

    /**
     * Compose a new tweet.
     */
    public void postTweet(int userId, int tweetId) {
        timestamp++;
        TweetNode node = new TweetNode(tweetId, timestamp);
        TweetNode curr = tweets.get(userId);
        if (curr != null) {
            node.next = curr;
        }
        tweets.put(userId, node);
    }

    /**
     * Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
     */
    public List<Integer> getNewsFeed(int userId) {
        pq.clear();
        List<Integer> res = new ArrayList<>();
        Set<Integer> set = followings.getOrDefault(userId, new HashSet<>());
        set.add(userId);
        for (int user : set) {
            if (tweets.get(user) != null)
                pq.offer(tweets.get(user));
        }
        int count = 0;
        while (count < 10 && !pq.isEmpty()) {
            TweetNode max = pq.poll();
            res.add(max.tweetId);
            pq.offer(max.next);
            count++;
        }
        return res;
    }

    /**
     * Follower follows a followee. If the operation is invalid, it should be a no-op.
     */
    public void follow(int followerId, int followeeId) {
        Set<Integer> set = followings.getOrDefault(followerId, new HashSet<>());
        set.add(followeeId);
        followings.put(followerId, set);
    }

    /**
     * Follower unfollows a followee. If the operation is invalid, it should be a no-op.
     */
    public void unfollow(int followerId, int followeeId) {
        Set<Integer> set = followings.get(followerId);
        if (set != null && set.contains(followeeId)) {
            set.remove(followeeId);
        }
    }
}

/**
 * Your Twitter object will be instantiated and called as such:
 * Twitter obj = new Twitter();
 * obj.postTweet(userId,tweetId);
 * List<Integer> param_2 = obj.getNewsFeed(userId);
 * obj.follow(followerId,followeeId);
 * obj.unfollow(followerId,followeeId);
 */
